const connection = require("../app/database");

class UserService {
	// 创建用户
	async create(user) {
		// 将用户存储到数据库
		const { name, password } = user;
		const statement = `INSERT INTO user (name, password) VALUES(?,?);`;
		const [result] = await connection.execute(statement, [name, password]);

		// 返回数据
		return result;
	}
	// 查询用户
	async getUserByName(name) {
		const statement = `SELECT * FROM user WHERE name = ?;`;
		const [result] = await connection.execute(statement, [name]);
		// 返回结果
		return result;
	}
	// 用户列表
	async getUserList(offset = 0, size = 20) {
		const statement = `SELECT * FROM user LIMIT ?, ?;`;
		const [result] = await connection.execute(statement, [offset, size]);
		// 返回结果
		return result;
	}
	// 更新用户
	async update(user, user_id) {
		const { name, password } = user;
		const statement = `UPDATE user SET name =?, password = ? WHERE id = ?;`;
		const [result] = await connection.execute(statement, [
			name,
			password,
			user_id
		]);

		// 返回数据
		return result;
	}
	// 保存头像地址
	async updateAvatarUrlById(user_id, avatarUrl) {
		const statement = `UPDATE user SET avatar_url = ? WHERE id = ?;`;
		const [result] = await connection.execute(statement, [
			avatarUrl,
			user_id
		]);
		// 返回结果
		return result;
	}
}

module.exports = new UserService();
